<template>
  <div class="payable-container">
    <!-- 搜索表单 -->
    <div class="search-box">
      <el-input
        v-model="searchParams.FlowingWaterNumber"
        placeholder="请输入流水号"
        clearable
        style="width: 200px"
        @keyup.enter="handleSearch"
      />
      <el-input
        v-model="searchParams.PayableManagementName"
        placeholder="请输入名称"
        clearable
        style="width: 200px"
        @keyup.enter="handleSearch"
      />
      <el-select
        v-model="searchParams.PayableManagementType"
        placeholder="请选择分类"
        clearable
        style="width: 200px"
      >
        <el-option
          v-for="category in categories"
          :key="category.financialCategoryId"
          :label="category.categoryName"
          :value="category.financialCategoryId"
        />
      </el-select>
      <el-input
        v-model="searchParams.Recipients"
        placeholder="请输入收款方"
        clearable
        style="width: 200px"
        @keyup.enter="handleSearch"
      />
      <el-select
        v-model="searchParams.State"
        placeholder="请选择状态"
        clearable
        style="width: 150px"
      >
        <el-option label="未审批" :value="0" />
        <el-option label="审批成功" :value="1" />
        <el-option label="审批失败" :value="2" />
        <el-option label="未付款" :value="5" />
        <el-option label="部分付款" :value="6" />
        <el-option label="已付清" :value="7" />
      </el-select>
      <el-date-picker
        v-model="dateRange"
        type="daterange"
        range-separator="至"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        style="width: 240px"
        @change="handleDateChange"
      />
      <el-button type="primary" @click="handleSearch">
        <el-icon><Search /></el-icon>搜索
      </el-button>
      <el-button @click="handleReset">
        <el-icon><Refresh /></el-icon>重置
      </el-button>
    </div>

    <!-- 操作按钮 -->
    <div class="action-box">
      <el-button 
        v-if="getCurrentRid() !== 2"
        type="primary" 
        @click="handleAdd"
      >
        <el-icon><Plus /></el-icon>新增
      </el-button>
      <el-button type="success" @click="handleExport" :loading="exportLoading">
        <el-icon><Download /></el-icon>导出Excel
      </el-button>
    </div>

    <!-- 数据表格 -->
    <el-table
      :data="tableData"
      border
      style="width: 100%"
      v-loading="loading"
      height="calc(100vh - 320px)"
      header-cell-class-name="custom-header"
      cell-class-name="custom-cell"
    >
      <el-table-column type="selection" width="50" align="center" />
      <el-table-column
        prop="flowingWaterNumber"
        label="流水号"
        align="center"
      />
      <el-table-column
        prop="payableManagementName"
        label="名称"
        align="center"
      />
      <el-table-column label="分类" align="center">
        <template #default="{ row }">
          {{ formatType(row.payableManagementType) }}
        </template>
      </el-table-column>
      <el-table-column prop="payer" label="付款方" align="center" />
      <el-table-column
        prop="recipients"
        label="收款方"
        align="center"
      />
      <el-table-column label="应收金额" align="center">
        <template #default="{ row }">
          {{ formatCurrency(row.amountReceivable) }}
        </template>
      </el-table-column>
      <el-table-column label="实收金额" align="center">
        <template #default="{ row }">
          {{ formatCurrency(row.paidInAmount) }}
        </template>
      </el-table-column>
      <el-table-column label="剩余金额" align="center">
        <template #default="{ row }">
          {{ formatCurrency(row.remainingAmount) }}
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center">
        <template #default="{ row }">
          <el-tag :type="getStateTagType(row.state)" disable-transitions>
            {{ formatState(row.state) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center">
        <template #default="{ row }">
          {{ formatTime(row.creatTime) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="320" align="center" fixed="right">
        <template #default="{ row }">
          <!-- 未审核时：编辑、删除、查看、审核 -->
          <template v-if="row.state === 0">
            <el-button
              v-if="getCurrentRid() !== 2"
              size="small"
              type="primary"
              icon="el-icon-edit"
              @click="handleEdit(row)"
              >编辑</el-button
            >
            <el-button
              v-if="getCurrentRid() !== 2"
              size="small"
              type="danger"
              icon="el-icon-delete"
              @click="handleDelete(row.payableManagementId)"
              >删除</el-button
            >
            <el-button
              size="small"
              type="info"
              icon="el-icon-view"
              @click="handleView(row)"
              >查看</el-button
            >
            <el-button
              v-if="getCurrentRid() === 2"
              size="small"
              type="warning"
              icon="el-icon-document-checked"
              @click="handleApproval(row)"
              >审批</el-button
            >
          </template>

          <!-- 审核通过后：付款、查看 -->
          <template v-else-if="row.state === 1 || row.state === 6">
            <el-button
              size="small"
              type="info"
              icon="el-icon-view"
              @click="handleView(row)"
              >查看</el-button
            >
            <el-button
              v-if="getCurrentRid() === 2 && canContinuePayment(row)"
              size="small"
              type="success"
              icon="el-icon-check"
              @click="handlePayment(row)"
              >付款</el-button
            >
            <el-button
              v-if="getCurrentRid() === 2 && !canContinuePayment(row)"
              size="small"
              type="warning"
              disabled
              :title="`已达到最大付款次数限制(${MAX_PAYMENT_TIMES}次)`"
              >付款已限制</el-button
            >
          </template>

          <!-- 已付清后：只有查看 -->
          <template v-else-if="row.state === 7">
            <el-button
              size="small"
              type="info"
              icon="el-icon-view"
              @click="handleView(row)"
              >查看</el-button
            >
          </template>

          <!-- 审批失败：编辑、删除、查看 -->
          <template v-else-if="row.state === 2">
            <el-button
              v-if="getCurrentRid() !== 2"
              size="small"
              type="primary"
              icon="el-icon-edit"
              @click="handleEdit(row)"
              >编辑</el-button
            >
            <el-button
              v-if="getCurrentRid() !== 2"
              size="small"
              type="danger"
              icon="el-icon-delete"
              @click="handleDelete(row.payableManagementId)"
              >删除</el-button
            >
            <el-button
              size="small"
              type="info"
              icon="el-icon-view"
              @click="handleView(row)"
              >查看</el-button
            >
          </template>

          <!-- 其他状态：默认显示查看 -->
          <template v-else>
            <el-button
              size="small"
              type="info"
              icon="el-icon-view"
              @click="handleView(row)"
              >查看</el-button
            >
          </template>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination-container">
      <el-pagination
        v-model:current-page="pagination.pageIndex"
        v-model:page-size="pagination.pageSize"
        :total="pagination.total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handlePageChange"
      />
    </div>

    <!-- 新增/编辑/查看对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isView ? '查看应付款' : isEdit ? '编辑应付款' : '新增应付款'"
      width="60%"
    >
      <el-form
        :model="formData"
        :rules="formRules"
        ref="formRef"
        label-width="100px"
        :class="{ 'view-mode': isView }"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="流水号:" prop="flowingWaterNumber">
              <el-input
                v-model="formData.flowingWaterNumber"
                :readonly="isView || isEdit"
                placeholder="系统自动生成"
              >
                <template #append v-if="!isView">
                  <el-button
                    @click="generateFlowingWaterNumber"
                    :disabled="isEdit"
                  >
                    <el-icon><Refresh /></el-icon>
                  </el-button>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="名称:" prop="payableManagementName">
              <el-input
                v-model="formData.payableManagementName"
                :readonly="isView"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="类别:" prop="payableManagementType">
              <el-select
                v-model="formData.payableManagementType"
                placeholder="请选择"
                style="width: 100%"
                :disabled="isView"
              >
                <el-option
                  v-for="category in categories"
                  :key="category.financialCategoryId"
                  :label="category.categoryName"
                  :value="category.financialCategoryId"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="最后付款日:">
              <el-date-picker
                v-model="formData.lastPaymentDate"
                type="datetime"
                placeholder="选择日期时间"
                format="YYYY-MM-DD HH:mm:ss"
                value-format="YYYY-MM-DDTHH:mm:ss"
                style="width: 100%"
                :disabled="isView"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="付款方:" prop="payer">
              <el-input v-model="formData.payer" :readonly="isView" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="收款方:" prop="recipients">
              <el-input v-model="formData.recipients" :readonly="isView" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="应收金额:" prop="amountReceivable">
              <el-input-number
                v-model="formData.amountReceivable"
                :min="0"
                :precision="2"
                style="width: 100%"
                :disabled="isView"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="付款次数:">
              <el-input-number
                v-model="formData.numberOfPayments"
                :min="0"
                style="width: 100%"
                :disabled="isView"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 查看模式下显示更多信息 -->
        <el-row :gutter="20" v-if="isView">
          <el-col :span="12">
            <el-form-item label="实收金额:">
              <el-input-number
                v-model="formData.paidInAmount"
                :precision="2"
                style="width: 100%"
                disabled
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="剩余金额:">
              <el-input-number
                v-model="formData.remainingAmount"
                :precision="2"
                style="width: 100%"
                disabled
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20" v-if="isView">
          <el-col :span="12">
            <el-form-item label="状态:">
              <el-input
                :value="formatState(formData.state)"
                readonly
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="付款机构:">
              <el-input
                v-model="formData.paymentInstitutions"
                readonly
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20" v-if="isView">
          <el-col :span="12">
            <el-form-item label="创建人:">
              <el-input
                v-model="formData.creatName"
                readonly
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="创建时间:">
              <el-input
                :value="formatTime(formData.creatTime)"
                readonly
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="备注:">
          <el-input
            v-model="formData.remark"
            type="textarea"
            :rows="4"
            :readonly="isView"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">{{
          isView ? "关闭" : "取消"
        }}</el-button>
        <el-button v-if="!isView" type="primary" @click="submitForm"
          >确定</el-button
        >
      </template>
    </el-dialog>

    <!-- 审批对话框 -->
    <el-dialog
      v-model="approvalDialogVisible"
      title="应收审批"
      width="60%"
      :before-close="handleApprovalClose"
      destroy-on-close
    >
      <div class="approval-dialog">
        <!-- 基本信息展示 -->
        <div class="payment-info">
          <el-descriptions title="付款信息" :column="2" border>
            <el-descriptions-item label="流水号">
              {{ currentApprovalPayment?.flowingWaterNumber || "-" }}
            </el-descriptions-item>
            <el-descriptions-item label="名称">
              {{ currentApprovalPayment?.payableManagementName || "-" }}
            </el-descriptions-item>
            <el-descriptions-item label="类别">
              {{ formatType(currentApprovalPayment?.payableManagementType) }}
            </el-descriptions-item>
            <el-descriptions-item label="最后付款日">
              {{ formatTime(currentApprovalPayment?.lastPaymentDate) }}
            </el-descriptions-item>
            <el-descriptions-item label="付款方">
              {{ currentApprovalPayment?.payer || "-" }}
            </el-descriptions-item>
            <el-descriptions-item label="收款方">
              {{ currentApprovalPayment?.recipients || "-" }}
            </el-descriptions-item>
            <el-descriptions-item label="应收金额">
              <span class="amount-text">{{
                formatCurrency(currentApprovalPayment?.amountReceivable || 0)
              }}</span>
            </el-descriptions-item>
            <el-descriptions-item label="付款次数">
              {{ currentApprovalPayment?.numberOfPayments || 0 }}
            </el-descriptions-item>
          </el-descriptions>

          <el-descriptions
            v-if="currentApprovalPayment?.remark"
            title="备注信息"
            :column="1"
            border
            style="margin-top: 20px"
          >
            <el-descriptions-item label="备注">
              {{ currentApprovalPayment.remark }}
            </el-descriptions-item>
          </el-descriptions>
        </div>

        <!-- 审批操作表单 -->
        <div class="approval-form">
          <h4>审批操作</h4>
          <el-form
            :model="approvalForm"
            :rules="approvalRules"
            ref="approvalFormRef"
            label-width="100px"
          >
            <el-form-item label="备注" prop="reason">
              <el-input
                v-model="approvalForm.reason"
                type="textarea"
                :rows="4"
                placeholder="请输入备注（必填）"
                maxlength="500"
                show-word-limit
              />
            </el-form-item>
          </el-form>
        </div>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleApprovalClose">取消</el-button>
          <el-button
            type="success"
            @click="handleApprove"
            :loading="approvalSubmitting"
            :disabled="!canApprove"
          >
            审核通过
          </el-button>
          <el-button
            type="danger"
            @click="handleReject"
            :loading="approvalSubmitting"
            :disabled="!canApprove"
          >
            审核不通过
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 付款对话框 -->
    <el-dialog v-model="paymentDialogVisible" title="新增实付" width="50%">
      <el-form
        :model="paymentFormData"
        :rules="paymentFormRules"
        ref="paymentFormRef"
        label-width="120px"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="流水号">
              <el-input v-model="paymentFormData.flowingWaterNumber" readonly />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="付款机构">
              <el-input v-model="paymentFormData.paymentInstitutions" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="付款方式" prop="payableManagementType">
              <el-select
                v-model="paymentFormData.payableManagementType"
                placeholder="请选择"
                style="width: 100%"
              >
                <el-option
                  v-for="category in categories"
                  :key="category.financialCategoryId"
                  :label="category.categoryName"
                  :value="category.financialCategoryId"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="最后付款日">
              <el-date-picker
                v-model="paymentFormData.lastPaymentDate"
                type="datetime"
                placeholder="选择日期时间"
                format="YYYY-MM-DD HH:mm:ss"
                value-format="YYYY-MM-DDTHH:mm:ss"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="付款金额" prop="paymentAmount">
              <el-input-number
                v-model="paymentFormData.paymentAmount"
                :min="0"
                :max="paymentFormData.remainingAmount"
                :precision="2"
                style="width: 100%"
                @change="calculateAfterPayment"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="剩余金额">
              <el-input-number
                v-model="paymentFormData.afterPaymentRemaining"
                readonly
                :precision="2"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="备注">
          <el-input
            v-model="paymentFormData.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入付款备注"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="paymentDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitPayment">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from "vue";
import { useRoute } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";

const route = useRoute();
import { Search, Refresh, Plus, Download } from "@element-plus/icons-vue";
import { type AxiosError } from "axios";
import { finread, finwrite } from "@/systeamaxios/sysaxiosHelpers";
import { useCounterStore } from "@/stores/counter";
import http from "@/http/axiosHelper";
const store = useCounterStore();
// 类型定义
interface PayableManagement {
  payableManagementId: number;
  flowingWaterNumber: string;
  payableManagementName: string;
  payableManagementType: number;
  recipients: string;
  amountReceivable: number;
  paidInAmount: number;
  remainingAmount: number;
  state: number;
  lastPaymentDate: string;
  payer: string;
  numberOfPayments: number;
  paymentInstitutions?: string | null;
  remark: string;
  rid: number; // 角色id
  creatTime: string;
  creatName: string;
  updateTime?: string | null;
  updateName?: string | null;
  deleteTime?: string | null;
  deleteName?: string | null;
  isDel: boolean;
}

interface ApiResponse<T = any> {
  code: number;
  message: string;
  totalPage: number;
  totalCount: number;
  pageDatas: T[];
  data: T;
}

interface SearchParams {
  PageIndex: number;
  PageSize: number;
  FlowingWaterNumber?: string;
  PayableManagementName?: string;
  PayableManagementType?: number;
  Recipients?: string;
  STime?: string;
  ETime?: string;
  State?: number;
  rid?: number;
  creatName?: string;
}

interface FinancialCategory {
  financialCategoryId: number;
  categoryNumber: string;
  categoryName: string;
  remark?: string;
  creatTime?: string;
  creatName?: string;
  updateTime?: string;
  updateName?: string;
  deleteTime?: string;
  deleteName?: string;
  isDel?: boolean;
}

interface PaymentMethod {
  paymentMethodId: number;
  methodName: string;
  methodCode: string;
  remark?: string;
  creatTime?: string;
  creatName?: string;
  updateTime?: string;
  updateName?: string;
  deleteTime?: string;
  deleteName?: string;
  isDel?: boolean;
}

// 接口基础路径
const API_BASE = {
  show: "/finread/api/FinancialCategory/ShowPayableManagementCommand",
  add: "/finwrite/api/PayableManagement/AddPayableManagementCommand",
  update: "/finwrite/api/PayableManagement/UpdPayableManagementCommand",
  delete: "/finwrite/api/PayableManagement/DelPayableManagementCommand",
  categories: "/finread/api/FinancialCategory/SelectFinancialCategoryCommand",
};
/*const API_BASE = {
  show: "/api/FinancialCategory/ShowPayableManagementCommand",
  add: "/api/PayableManagement/AddPayableManagementCommand",
  update: "/api/PayableManagement/UpdPayableManagementCommand",
  delete: "/api/PayableManagement/DelPayableManagementCommand",
  categories: "/api/FinancialCategory/SelectFinancialCategoryCommand",
};*/

// 获取当前登录用户名
const getCurrentUserName = (): string => {
  const userName = localStorage.getItem("userName") || localStorage.getItem("currentUser") || "admin";
  console.log("Getting current userName:", userName);
  return userName;
};

// 获取当前用户的rid
const getCurrentRid = (): number => {
  const storedRid = localStorage.getItem("Rid");
  const rid = storedRid !== null ? Number(storedRid) : 2;
  console.log("Getting current rid:", rid, "stored value:", storedRid);
  return rid;
};

// 响应式数据
const tableData = ref<PayableManagement[]>([]);
const loading = ref(false);
const exportLoading = ref(false);
const dialogVisible = ref(false);
const isEdit = ref(false);
const isView = ref(false);
const formRef = ref();
const categories = ref<FinancialCategory[]>([]);
const paymentMethods = ref<PaymentMethod[]>([]);
const paymentDialogVisible = ref(false);
const paymentFormRef = ref();

// 新增变量
const dateRange = ref<[Date, Date] | null>(null);

// 审批相关数据
const approvalDialogVisible = ref(false);
const currentApprovalPayment = ref<PayableManagement | null>(null);
const approvalFormRef = ref();
const approvalSubmitting = ref(false);

// 审批表单
const approvalForm = reactive({
  reason: "",
});

// 审批表单验证规则
const approvalRules = {
  reason: [
    { required: true, message: "请输入备注", trigger: "blur" },
    { min: 2, message: "备注至少2个字符", trigger: "blur" },
  ],
};

// 计算属性 - 是否可以审批
const canApprove = computed(() => {
  return currentApprovalPayment.value?.state === 0;
});

// 分页参数
const pagination = reactive({
  pageIndex: 1,
  pageSize: 15, // 修改默认分页为15条
  total: 0,
});

// 搜索参数
const searchParams = reactive<SearchParams>({
  PageIndex: 1,
  PageSize: 15, // 修改默认分页为15条
  FlowingWaterNumber: "",
  PayableManagementName: "",
  PayableManagementType: undefined,
  Recipients: "",
  STime: "",
  ETime: "",
  State: undefined,
  rid: undefined, // 将在fetchData中设置
});

// 付款表单数据
interface PaymentFormData {
  payableManagementId: number;
  flowingWaterNumber: string;
  paymentInstitutions?: string;
  paymentMethod: string;
  lastPaymentDate: string;
  paymentAmount: number;
  remainingAmount: number;
  afterPaymentRemaining: number;
  payableManagementType: number;
  remark: string;
}

const paymentFormData = reactive<PaymentFormData>({
  payableManagementId: 0,
  flowingWaterNumber: "",
  paymentInstitutions: "",
  paymentMethod: "",
  lastPaymentDate: "",
  paymentAmount: 0,
  remainingAmount: 0,
  afterPaymentRemaining: 0,
  payableManagementType: undefined as any,
  remark: "",
});

// 表单数据
const formData = reactive<PayableManagement>({
  payableManagementId: 0,
  flowingWaterNumber: "",
  payableManagementName: "",
  payableManagementType: undefined as any,
  recipients: "",
  amountReceivable: 0,
  paidInAmount: 0,
  remainingAmount: 0,
  state: 0,
  lastPaymentDate: "",
  payer: "",
  numberOfPayments: 0,
  paymentInstitutions: "",
  remark: "",
  rid: getCurrentRid(), // 使用helper函数获取rid
  creatTime: "",
  creatName: getCurrentUserName(),
  updateTime: "",
  updateName: getCurrentUserName(),
  deleteTime: "",
  deleteName: "",
  isDel: false,
});

// 付款表单验证规则
const paymentFormRules = {
  paymentMethod: [
    { required: true, message: "请选择付款方式", trigger: "change" },
  ],
  paymentAmount: [
    { required: true, message: "请输入付款金额", trigger: "blur" },
    {
      type: "number",
      min: 0.01,
      message: "付款金额必须大于0",
      trigger: "blur",
    },
  ],
};

// 表单验证规则
const formRules = {
  flowingWaterNumber: [
    { required: true, message: "流水号不能为空", trigger: "blur" },
  ],
  payableManagementName: [
    { required: true, message: "请输入名称", trigger: "blur" },
  ],
  payableManagementType: [
    { required: true, message: "请选择分类", trigger: "change" },
  ],
  recipients: [{ required: true, message: "请输入收款方", trigger: "blur" }],
  amountReceivable: [
    { required: true, message: "请输入应收金额", trigger: "blur" },
  ],
  payer: [{ required: true, message: "请输入付款方", trigger: "blur" }],
};

// 最大付款次数限制
const MAX_PAYMENT_TIMES = 10; // 最大付款次数限制

// 计算剩余金额
const computeRemainingAmount = () => {
  formData.remainingAmount = formData.amountReceivable - formData.paidInAmount;
};

// 获取分类数据
const fetchCategories = async () => {
  try {
    const response = await http.get<{
      code: number;
      message: string;
      data: FinancialCategory[];
    }>(API_BASE.categories);

    if (response.data.code === 200) {
      categories.value = response.data.data || [];
    } else {
      ElMessage.warning(response.data.message || "获取分类数据失败");
    }
  } catch (error) {
    const err = error as AxiosError<{
      code: number;
      message: string;
      data: FinancialCategory[];
    }>;
    ElMessage.error(err.response?.data?.message || "获取分类数据失败");
  }
};

// 获取数据
const fetchData = async () => {
  loading.value = true;
  try {
    // 更新搜索参数中的分页信息
    searchParams.PageIndex = pagination.pageIndex;
    searchParams.PageSize = pagination.pageSize;

    // 权限控制：RID == 2或RID == 13的用户可以看到所有人的数据，其他用户只能看到自己创建的数据
    const currentRid = getCurrentRid();
    const currentUserName = getCurrentUserName();
    
    if (currentRid === 2 || currentRid === 13) {
      // 管理员用户(rid==2)和特定用户(rid==13)可以查看所有数据
      searchParams.rid = undefined;
      searchParams.creatName = undefined;
    } else {
      // 其他角色用户，只能查看自己创建的数据
      searchParams.rid = currentRid;
      searchParams.creatName = currentUserName;
    }

    console.log("当前用户RID:", currentRid);
    console.log("当前用户名:", currentUserName);
    console.log("查询参数:", searchParams);
    
    const response = await http.get<ApiResponse<PayableManagement>>(
      API_BASE.show,
      {
        params: searchParams,
      }
    );

    if (response.data.code === 200) {
      tableData.value = response.data.pageDatas || [];
      pagination.total = response.data.totalCount || 0;
      ElMessage.success(response.data.message);
    } else {
      ElMessage.warning(response.data.message || "获取数据失败");
    }
  } catch (error) {
    const err = error as AxiosError<ApiResponse>;
    ElMessage.error(err.response?.data?.message || "请求失败");
  } finally {
    loading.value = false;
  }
};

// 搜索处理
const handleSearch = () => {
  // 权限控制：RID == 2的用户能看见所有人的数据，其他用户只能看见自己创建的数据
  const currentRid = getCurrentRid();
  const currentUserName = getCurrentUserName();
  console.log("搜索时当前用户RID:", currentRid);
  
  if (currentRid === 2) {
    // 管理员用户(rid==2)可以查看所有数据
    searchParams.rid = undefined;
    searchParams.creatName = undefined;
  } else {
    // 其他角色用户，只能查看自己创建的数据
    searchParams.rid = currentRid;
    searchParams.creatName = currentUserName;
  }
  
  pagination.pageIndex = 1;
  fetchData();
};

// 重置搜索
const handleReset = () => {
  // 权限控制：RID == 2的用户能看见所有人的数据，其他用户只能看见自己创建的数据
  const currentRid = getCurrentRid();
  const currentUserName = getCurrentUserName();
  console.log("重置时当前用户RID:", currentRid);
  
  // 根据用户权限设置rid和creatName参数
  let ridParam: number | undefined;
  let creatNameParam: string | undefined;
  if (currentRid === 2) {
    // 管理员用户(rid==2)可以查看所有数据
    ridParam = undefined;
    creatNameParam = undefined;
  } else {
    // 其他角色用户，只能查看自己创建的数据
    ridParam = currentRid;
    creatNameParam = currentUserName;
  }
  
  Object.assign(searchParams, {
    PageIndex: 1,
    PageSize: 15, // 修改默认分页为15条
    FlowingWaterNumber: "",
    PayableManagementName: "",
    PayableManagementType: undefined,
    Recipients: "",
    STime: "",
    ETime: "",
    State: undefined,
    rid: ridParam,
    creatName: creatNameParam,
  });
  pagination.pageIndex = 1;
  fetchData();
};

// 分页大小变化
const handleSizeChange = (size: number) => {
  pagination.pageSize = size;
  // 权限控制：保持当前用户的权限设置
  const currentRid = getCurrentRid();
  const currentUserName = getCurrentUserName();
  if (currentRid === 2) {
    // 管理员用户(rid==2)可以查看所有数据
    searchParams.rid = undefined;
    searchParams.creatName = undefined;
  } else {
    // 其他角色用户，只能查看自己创建的数据
    searchParams.rid = currentRid;
    searchParams.creatName = currentUserName;
  }
  fetchData();
};

// 页码变化
const handlePageChange = (page: number) => {
  pagination.pageIndex = page;
  // 权限控制：保持当前用户的权限设置
  const currentRid = getCurrentRid();
  const currentUserName = getCurrentUserName();
  if (currentRid === 2) {
    // 管理员用户(rid==2)可以查看所有数据
    searchParams.rid = undefined;
    searchParams.creatName = undefined;
  } else {
    // 其他角色用户，只能查看自己创建的数据
    searchParams.rid = currentRid;
    searchParams.creatName = currentUserName;
  }
  fetchData();
};

// 生成流水号
const generateFlowingWaterNumber = () => {
  const now = new Date();
  const year = now.getFullYear();
  const month = String(now.getMonth() + 1).padStart(2, "0");
  const day = String(now.getDate()).padStart(2, "0");
  const hours = String(now.getHours()).padStart(2, "0");
  const minutes = String(now.getMinutes()).padStart(2, "0");
  const seconds = String(now.getSeconds()).padStart(2, "0");
  const milliseconds = String(now.getMilliseconds()).padStart(3, "0");

  // 格式: YF + YYYYMMDDHHMMSS + 毫秒后3位
  formData.flowingWaterNumber = `YF${year}${month}${day}${hours}${minutes}${seconds}${milliseconds}`;
};

// 新增
const handleAdd = () => {
  // 权限验证：rid==2的用户不能新增，但rid==0的用户可以新增
  if (getCurrentRid() === 2) {
    ElMessage.error("您没有新增权限");
    return;
  }

  isEdit.value = false;
  isView.value = false;
  Object.assign(formData, {
    payableManagementId: 0,
    flowingWaterNumber: "",
    payableManagementName: "",
    payableManagementType: undefined,
    recipients: "",
    amountReceivable: 0,
    paidInAmount: 0,
    remainingAmount: 0,
    state: 0,
    lastPaymentDate: "",
    payer: "",
    numberOfPayments: 0,
    paymentInstitutions: "",
    remark: "",
    rid: getCurrentRid(), // 使用helper函数获取rid
    creatName: getCurrentUserName(),
    updateName: getCurrentUserName(),
    creatTime: new Date().toISOString(),
    updateTime: new Date().toISOString(),
    deleteTime: "",
    deleteName: "",
    isDel: false,
  });

  // 自动生成流水号
  generateFlowingWaterNumber();

  dialogVisible.value = true;
};

// 编辑
const handleEdit = (row: PayableManagement) => {
  // 权限验证：rid==2的用户不能编辑，但rid==0的用户可以编辑
  if (getCurrentRid() === 2) {
    ElMessage.error("您没有编辑权限");
    return;
  }

  isEdit.value = true;
  isView.value = false;

  // 处理日期格式转换
  let formattedDate = "";
  if (row.lastPaymentDate) {
    try {
      const date = new Date(row.lastPaymentDate);
      if (!isNaN(date.getTime())) {
        formattedDate = date.toISOString().slice(0, 19);
      }
    } catch (error) {
      console.error(
        "编辑时日期转换错误:",
        error,
        "原始日期:",
        row.lastPaymentDate
      );
    }
  }

  Object.assign(formData, {
    ...row,
    lastPaymentDate: formattedDate,
  });

  console.log("编辑表单数据:", formData);
  dialogVisible.value = true;
};

// 查看
const handleView = (row: PayableManagement) => {
  isEdit.value = false;
  isView.value = true;

  // 处理日期格式转换
  let formattedDate = "";
  if (row.lastPaymentDate) {
    try {
      const date = new Date(row.lastPaymentDate);
      if (!isNaN(date.getTime())) {
        formattedDate = date.toISOString().slice(0, 19);
      }
    } catch (error) {
      console.error(
        "查看时日期转换错误:",
        error,
        "原始日期:",
        row.lastPaymentDate
      );
    }
  }

  Object.assign(formData, {
    ...row,
    lastPaymentDate: formattedDate,
  });

  console.log("查看表单数据:", formData);
  dialogVisible.value = true;
};

// 审批
const handleApproval = (row: PayableManagement) => {
  currentApprovalPayment.value = row;

  // 重置审批表单
  approvalForm.reason = "";
  approvalFormRef.value?.clearValidate();

  approvalDialogVisible.value = true;
};

// 处理审批通过
const handleApprove = async () => {
  if (!currentApprovalPayment.value) return;

  try {
    await approvalFormRef.value?.validate();

    await ElMessageBox.confirm("确认审批通过该付款申请吗？", "确认审批", {
      confirmButtonText: "确认",
      cancelButtonText: "取消",
      type: "success",
    });

    approvalSubmitting.value = true;

    // 调用审批通过API - 使用完整的数据结构
    const approvalData = {
      payableManagementId: currentApprovalPayment.value.payableManagementId,
      flowingWaterNumber: currentApprovalPayment.value.flowingWaterNumber,
      payableManagementName: currentApprovalPayment.value.payableManagementName,
      payableManagementType: currentApprovalPayment.value.payableManagementType,
      recipients: currentApprovalPayment.value.recipients,
      amountReceivable: currentApprovalPayment.value.amountReceivable,
      paidInAmount: currentApprovalPayment.value.paidInAmount,
      remainingAmount: currentApprovalPayment.value.remainingAmount,
      state: 1, // 审批通过，状态改为审批成功
      lastPaymentDate: currentApprovalPayment.value.lastPaymentDate,
      payer: currentApprovalPayment.value.payer,
      numberOfPayments: currentApprovalPayment.value.numberOfPayments,
      paymentInstitutions:
        currentApprovalPayment.value.paymentInstitutions || null,
      remark: approvalForm.reason, // 使用审批意见作为备注
      rid: getCurrentRid(), // 使用helper函数获取rid
      creatTime: currentApprovalPayment.value.creatTime,
      creatName: currentApprovalPayment.value.creatName,
      updateTime: new Date().toISOString(),
      updateName: getCurrentUserName(),
      deleteTime: currentApprovalPayment.value.deleteTime,
      deleteName: currentApprovalPayment.value.deleteName,
      isDel: currentApprovalPayment.value.isDel,
    };

    const response = await http.post(API_BASE.update, approvalData);

    if (response.data.code === 200) {
      // 更新本地数据状态
      const index = tableData.value.findIndex(
        (item) =>
          item.payableManagementId ===
          currentApprovalPayment.value!.payableManagementId
      );
      if (index !== -1) {
        tableData.value[index].state = 1; // 审批通过，状态改为审批成功
        tableData.value[index].remark = approvalForm.reason; // 保存备注
        tableData.value[index].updateTime = new Date().toISOString();
        tableData.value[index].updateName = getCurrentUserName();
      }
      
      // 审批成功后重新获取数据，确保数据正确显示
      await fetchData();
    } else {
      throw new Error(response.data.message || "审批失败");
    }

    ElMessage.success("审批通过成功");
    handleApprovalClose();
  } catch (error: any) {
    if (error !== "cancel") {
      ElMessage.error("审批失败");
    }
  } finally {
    approvalSubmitting.value = false;
  }
};

// 处理审批拒绝
const handleReject = async () => {
  if (!currentApprovalPayment.value) return;

  try {
    await approvalFormRef.value?.validate();

    await ElMessageBox.confirm("确认拒绝该付款申请吗？", "确认拒绝", {
      confirmButtonText: "确认",
      cancelButtonText: "取消",
      type: "warning",
    });

    approvalSubmitting.value = true;

    // 调用审批拒绝API - 使用完整的数据结构
    const approvalData = {
      payableManagementId: currentApprovalPayment.value.payableManagementId,
      flowingWaterNumber: currentApprovalPayment.value.flowingWaterNumber,
      payableManagementName: currentApprovalPayment.value.payableManagementName,
      payableManagementType: currentApprovalPayment.value.payableManagementType,
      recipients: currentApprovalPayment.value.recipients,
      amountReceivable: currentApprovalPayment.value.amountReceivable,
      paidInAmount: currentApprovalPayment.value.paidInAmount,
      remainingAmount: currentApprovalPayment.value.remainingAmount,
      state: 2, // 审批拒绝
      lastPaymentDate: currentApprovalPayment.value.lastPaymentDate,
      payer: currentApprovalPayment.value.payer,
      numberOfPayments: currentApprovalPayment.value.numberOfPayments,
      paymentInstitutions:
        currentApprovalPayment.value.paymentInstitutions || null,
      remark: approvalForm.reason, // 使用审批意见作为备注
      rid: getCurrentRid(), // 使用helper函数获取rid
      creatTime: currentApprovalPayment.value.creatTime,
      creatName: currentApprovalPayment.value.creatName,
      updateTime: new Date().toISOString(),
      updateName: getCurrentUserName(),
      deleteTime: currentApprovalPayment.value.deleteTime,
      deleteName: currentApprovalPayment.value.deleteName,
      isDel: currentApprovalPayment.value.isDel,
    };

    const response = await http.post(API_BASE.update, approvalData);

    if (response.data.code === 200) {
      // 更新本地数据状态
      const index = tableData.value.findIndex(
        (item) =>
          item.payableManagementId ===
          currentApprovalPayment.value!.payableManagementId
      );
      if (index !== -1) {
        tableData.value[index].state = 2; // 审批拒绝
        tableData.value[index].remark = approvalForm.reason; // 保存备注
        tableData.value[index].updateTime = new Date().toISOString();
        tableData.value[index].updateName = getCurrentUserName();
      }
      
      // 审批拒绝后重新获取数据，确保数据正确显示
      await fetchData();
    } else {
      throw new Error(response.data.message || "审批失败");
    }

    ElMessage.success("审批拒绝成功");
    handleApprovalClose();
  } catch (error: any) {
    if (error !== "cancel") {
      ElMessage.error("审批失败");
    }
  } finally {
    approvalSubmitting.value = false;
  }
};

// 关闭审批对话框
const handleApprovalClose = () => {
  approvalDialogVisible.value = false;
  currentApprovalPayment.value = null;
  approvalForm.reason = "";
  approvalFormRef.value?.clearValidate();
};

// 检查是否可以继续付款
const canContinuePayment = (row: PayableManagement): boolean => {
  const currentPaymentTimes = row.numberOfPayments || 0;
  return currentPaymentTimes < MAX_PAYMENT_TIMES;
};

// 付款
const handlePayment = (row: PayableManagement) => {
  Object.assign(paymentFormData, {
    payableManagementId: row.payableManagementId,
    flowingWaterNumber: row.flowingWaterNumber,
    paymentInstitutions: row.payer || "", // 将付款方自动填入付款机构
    paymentMethod: "", // 每次都重置为未选中
    lastPaymentDate: new Date().toISOString().slice(0, 19),
    paymentAmount: 0,
    remainingAmount: row.remainingAmount,
    afterPaymentRemaining: row.remainingAmount,
    payableManagementType: undefined,
    remark: "",
  });
  paymentDialogVisible.value = true;
};

// 计算付款后剩余金额
const calculateAfterPayment = () => {
  paymentFormData.afterPaymentRemaining =
    paymentFormData.remainingAmount - paymentFormData.paymentAmount;
};

// 提交付款
const submitPayment = async () => {
  try {
    await paymentFormRef.value?.validate();

    console.log("Payment form data:", paymentFormData);
    console.log(
      "Payment institutions value:",
      paymentFormData.paymentInstitutions
    );

    // 这里需要调用付款API，暂时模拟更新原记录
    const originalRecord = tableData.value.find(
      (item) => item.payableManagementId === paymentFormData.payableManagementId
    );

    if (!originalRecord) {
      ElMessage.error("找不到原始记录");
      return;
    }

    const updatedData = {
      ...originalRecord,
      paidInAmount:
        (originalRecord.paidInAmount || 0) + paymentFormData.paymentAmount,
      remainingAmount: paymentFormData.afterPaymentRemaining,
      lastPaymentDate: paymentFormData.lastPaymentDate
        ? paymentFormData.lastPaymentDate + ".000Z"
        : null,
      numberOfPayments: (originalRecord.numberOfPayments || 0) + 1,
      state: paymentFormData.afterPaymentRemaining <= 0 ? 7 : 6, // 0:未审批, 1:已审批, 2:审批失败，5:未付款, 6:部分付款, 7:已付清
      updateName: getCurrentUserName(),
      updateTime: new Date().toISOString(),
      paymentInstitutions: paymentFormData.paymentInstitutions?.trim() || null,
      remark: paymentFormData.remark?.trim() || originalRecord.remark,
      rid: getCurrentRid(), // 确保rid有值
    };

    console.log("Updated data for payment:", updatedData);

    const response = await http.post(API_BASE.update, updatedData);

    if (response.data.code === 200) {
      ElMessage.success("付款成功");
      paymentDialogVisible.value = false;
      fetchData();
    } else {
      ElMessage.warning(response.data.message || "付款失败");
    }
  } catch (error) {
    const err = error as AxiosError<ApiResponse>;
    ElMessage.error(err.response?.data?.message || "付款失败");
  }
};

// 删除
const handleDelete = async (id: number) => {
  // 权限验证：rid==2的用户不能删除，但rid==0的用户可以删除
  if (getCurrentRid() === 2) {
    ElMessage.error("您没有删除权限");
    return;
  }

  try {
    await ElMessageBox.confirm("确认删除该记录吗？", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    });

    const response = await http.post(
      `${API_BASE.delete}?PayableManagementId=${id}`
    );
    if (response.data.code === 200) {
      ElMessage.success(response.data.message);
      fetchData();
    } else {
      ElMessage.warning(response.data.message || "删除失败");
    }
  } catch (error) {
    if (error !== "cancel") {
      const err = error as AxiosError<ApiResponse>;
      ElMessage.error(err.response?.data?.message || "删除失败");
    }
  }
};

// 提交表单
const submitForm = async () => {
  // 权限验证：rid==2的用户不能提交表单，但rid==0的用户可以提交
  if (getCurrentRid() === 2) {
    ElMessage.error("您没有操作权限");
    return;
  }

  // 查看模式下不允许提交
  if (isView.value) {
    return;
  }

  try {
    await formRef.value?.validate();

    // 计算剩余金额
    computeRemainingAmount();

    // 准备提交数据，确保包含所有必要字段
    const submitData = {
      payableManagementId: formData.payableManagementId || 0,
      flowingWaterNumber: formData.flowingWaterNumber?.trim() || "",
      payableManagementName: formData.payableManagementName?.trim() || "",
      payableManagementType: Number(formData.payableManagementType) || 0,
      recipients: formData.recipients?.trim() || "",
      amountReceivable: Number(formData.amountReceivable) || 0,
      paidInAmount: Number(formData.paidInAmount) || 0,
      remainingAmount: Number(formData.remainingAmount) || 0,
      state: 0, // 新增时默认为未付款状态
      lastPaymentDate: formData.lastPaymentDate
        ? formData.lastPaymentDate + ".000Z"
        : null,
      payer: formData.payer?.trim() || "",
      numberOfPayments: Number(formData.numberOfPayments) || 0,
      paymentInstitutions: formData.paymentInstitutions?.trim() || null,
      remark: formData.remark?.trim() || "",
      rid: getCurrentRid(), // 使用helper函数获取rid
      creatTime: isEdit.value
        ? formData.creatTime || new Date().toISOString()
        : new Date().toISOString(),
      creatName: isEdit.value ? formData.creatName || getCurrentUserName() : getCurrentUserName(),
      // 编辑时设置更新信息，新增时设为null
      updateTime: isEdit.value ? new Date().toISOString() : null,
      updateName: isEdit.value ? getCurrentUserName() : null,
      deleteTime: null,
      deleteName: null,
      isDel: false,
    };

    // 清理空字符串，将其转为null（除了remark、creatTime、creatName、lastPaymentDate、rid字段）
    (Object.keys(submitData) as (keyof typeof submitData)[]).forEach((key) => {
      if (
        submitData[key] === "" &&
        key !== "remark" &&
        key !== "creatTime" &&
        key !== "creatName" &&
        key !== "lastPaymentDate" &&
        key !== "rid"
      ) {
        (submitData as any)[key] = null;
      }
    });

    // 调试信息
    console.log("LocalStorage Rid:", localStorage.getItem("Rid"));
    console.log("提交数据:", submitData);
    console.log("提交数据中的rid:", submitData.rid);
    console.log("是否编辑模式:", isEdit.value);
    console.log("API地址:", isEdit.value ? API_BASE.update : API_BASE.add);

    let response;
    if (isEdit.value) {
      response = await http.post(API_BASE.update, submitData);
    } else {
      response = await http.post(API_BASE.add, submitData);
    }

    if (response.data.code === 200) {
      ElMessage.success(response.data.message);
      dialogVisible.value = false;
      fetchData();
    } else {
      console.error("业务错误:", response.data);
      ElMessage.warning(response.data.message || "操作失败");
    }
  } catch (error) {
    const err = error as AxiosError<ApiResponse>;
    console.error("提交错误详情:", error);
    console.error("错误响应:", err.response?.data);
    console.error("错误状态:", err.response?.status);

    if (err.response?.status === 400) {
      ElMessage.error("请求参数错误，请检查输入数据");
    } else if (err.response?.status === 500) {
      ElMessage.error("服务器内部错误，请稍后重试");
    } else {
      ElMessage.error(err.response?.data?.message || "提交失败");
    }
  }
};

// 日期范围变化处理
const handleDateChange = (dates: [Date, Date] | null) => {
  if (dates) {
    searchParams.STime = dates[0].toISOString().split('T')[0];
    searchParams.ETime = dates[1].toISOString().split('T')[0];
  } else {
    searchParams.STime = "";
    searchParams.ETime = "";
  }
};

// 导出功能
const handleExport = async () => {
  if (!tableData.value.length) {
    ElMessage.warning('暂无数据可导出');
    return;
  }
  
  exportLoading.value = true;
  try {
    // 这里可以添加导出逻辑，暂时显示成功消息
    ElMessage.success('导出功能待实现');
  } catch (error) {
    ElMessage.error('导出失败，请重试');
  } finally {
    exportLoading.value = false;
  }
};

// 格式化函数
const formatTime = (time: string | null | undefined) => {
  if (!time || time === "" || time === "null") return "-";
  try {
    const date = new Date(time);
    if (isNaN(date.getTime())) return "-";
    return date.toLocaleString("zh-CN", {
      year: "numeric",
      month: "2-digit",
      day: "2-digit",
      hour: "2-digit",
      minute: "2-digit",
      second: "2-digit",
    });
  } catch (error) {
    console.error("日期格式化错误:", error, "原始值:", time);
    return "-";
  }
};

const formatNullValue = (value: any) => {
  return value === null || value === undefined || value === "" ? "-" : value;
};

const formatCurrency = (amount: number) => {
  return new Intl.NumberFormat("zh-CN", {
    style: "currency",
    currency: "CNY",
  }).format(amount);
};

const formatType = (type: number | undefined) => {
  if (!type) return "-";
  const category = categories.value.find(
    (cat) => cat.financialCategoryId === type
  );
  return category ? category.categoryName : "-";
};

const formatPaymentMethod = (methodCode: string) => {
  const method = paymentMethods.value.find(
    (method) => method.methodCode === methodCode
  );
  return method ? method.methodName : methodCode || "-";
};

const formatState = (state: number) => {
  const stateMap: { [key: number]: string } = {
    0: "未审批",
    1: "审批成功",
    2: "已驳回",
    5: "未付款",
    6: "部分付款",
    7: "已付清",
  };
  return stateMap[state] || "-";
};

const getStateTagType = (state: number) => {
  const tagTypeMap: { [key: number]: string } = {
    0: "warning", // 未审批 - 警告色
    1: "success", // 审批成功 - 成功色
    2: "danger", // 已驳回 - 危险色
    5: "info", // 未付款 - 信息色
    6: "primary", // 部分付款 - 主要色
    7: "success", // 已付清 - 成功色
  };
  return tagTypeMap[state] || "";
};

// 处理从采购页面传来的数据
const handleData = () => {
  // 处理从采购页面传来的数据
  if (route.query.fromPurchase === "true" && route.query.data) {
    try {
      const purchaseData = JSON.parse(route.query.data as string);

      // 自动打开新增对话框并填充数据
      isEdit.value = false;
      Object.assign(formData, {
        payableManagementId: 0,
        flowingWaterNumber: "",
        payableManagementName: purchaseData.productName || "", // 产品名称对应名称
        payableManagementType: undefined,
        recipients: purchaseData.vendorName || "", // 供应商对应收款方
        amountReceivable: purchaseData.total || 0, // 总额对应应收金额
        paidInAmount: 0,
        remainingAmount: purchaseData.total || 0,
        state: 0,
        lastPaymentDate: "",
        payer: "公司",
        numberOfPayments: 0,
        paymentInstitutions: "",
        remark: `采购入账 - 采购单号: ${purchaseData.purchaseId}, 产品规格: ${
          purchaseData.productSpecs || ""
        }`,
        rid: getCurrentRid(), // 使用helper函数获取rid
        creatName: getCurrentUserName(),
        updateName: getCurrentUserName(),
        creatTime: new Date().toISOString(),
        updateTime: new Date().toISOString(),
        deleteTime: "",
        deleteName: "",
        isDel: false,
      });

      // 自动生成流水号
      generateFlowingWaterNumber();

      // 显示对话框
      dialogVisible.value = true;

      ElMessage.success("已自动填充采购数据，请确认后提交");
    } catch (error) {
      ElMessage.error("解析采购数据失败");
    }
  }
};

// 初始化加载数据
onMounted(async () => {
  // 调试：检查localStorage中的rid值
  console.log("LocalStorage Rid:", localStorage.getItem("Rid"));

  // 确保rid有值，如果没有则设置默认值
  const currentRid = getCurrentRid();
  console.log("Final rid value:", currentRid);

  // 如果localStorage中没有Rid，设置默认值
  if (!localStorage.getItem("Rid")) {
    localStorage.setItem("Rid", "2");
    console.log("Set default Rid to localStorage:", "2");
  }

  // 权限控制：根据用户权限设置初始rid和creatName参数
  const currentUserName = getCurrentUserName();
  if (currentRid === 2 || currentRid === 0) {
    // 管理员用户(rid==2)和普通用户(rid==0)都可以查看所有数据
    searchParams.rid = undefined;
    searchParams.creatName = undefined;
  } else {
    // 其他角色用户，只能查看自己创建的数据
    searchParams.rid = currentRid;
    searchParams.creatName = currentUserName;
  }

  await fetchCategories();
  fetchData();

  // 检查是否有从其他页面传来的数据
  handleData();
});
</script>

<style scoped>
.payable-container {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.search-box {
  background: white;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
  align-items: center;
}

.action-box {
  background: white;
  padding: 15px 20px;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.pagination-container {
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  margin-top: 20px;
  text-align: right;
}

.custom-header {
  text-align: center;
  font-weight: bold;
  background: #fafafa;
}

.custom-cell {
  text-align: center;
}

/* 表格样式 */
:deep(.el-table) {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

:deep(.el-table__header) {
  background-color: #f8f9fa;
}

:deep(.el-table th) {
  background-color: #f8f9fa !important;
  color: #333;
  font-weight: 600;
}

/* 分页样式 */
:deep(.el-pagination) {
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  margin-top: 20px;
}

/* 对话框样式 */
:deep(.el-dialog) {
  border-radius: 8px;
}

:deep(.el-dialog__header) {
  background-color: #f8f9fa;
  border-radius: 8px 8px 0 0;
}

/* 按钮样式 */
.el-button + .el-button {
  margin-left: 8px;
}

/* 状态标签样式 */
:deep(.el-tag) {
  font-weight: 500;
}

/* 审批对话框样式 */
.approval-dialog {
  max-height: 70vh;
  overflow-y: auto;
}

.payment-info {
  margin-bottom: 20px;
}

.amount-text {
  font-weight: bold;
  color: #e6a23c;
}

.approval-form {
  margin-top: 20px;
  padding: 15px;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
}

.approval-form h4 {
  margin: 0 0 15px 0;
  color: #303133;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

:deep(.el-descriptions__label) {
  font-weight: bold;
}

:deep(.el-timeline-item__timestamp) {
  font-size: 12px;
  color: #909399;
}

/* 查看模式样式 */
.view-mode .el-input__inner,
.view-mode .el-textarea__inner {
  background-color: #f5f7fa;
  border-color: #e4e7ed;
  color: #606266;
}

.view-mode .el-input-number .el-input__inner {
  background-color: #f5f7fa;
}

.view-mode .el-select .el-input__inner {
  background-color: #f5f7fa;
}
</style>
